"""
监控和分析相关模型
"""
from tortoise import fields
from .base import BaseModel


class SensorData(BaseModel):
    """传感器数据模型"""
    
    # 设备信息
    device = fields.ForeignKeyField("models.TrackingDevice", related_name="sensor_data", description="追踪设备")
    
    # 传感器类型
    sensor_type = fields.CharField(
        max_length=20,
        description="传感器类型: temperature-温度, humidity-湿度, pressure-压力, vibration-震动, light-光照"
    )
    
    # 数据值
    value = fields.DecimalField(max_digits=10, decimal_places=4, description="传感器数值")
    unit = fields.CharField(max_length=20, description="单位")
    
    # 质量指标
    quality = fields.CharField(
        max_length=20,
        default="good",
        description="数据质量: excellent-优秀, good-良好, fair-一般, poor-较差"
    )
    
    # 时间信息
    recorded_at = fields.DatetimeField(description="记录时间")
    
    class Meta:
        table = "sensor_data"
        table_description = "传感器数据表"
        indexes = [
            ["device", "sensor_type", "recorded_at"],
            ["recorded_at"],
        ]


class Alert(BaseModel):
    """警报模型"""
    
    # 警报基本信息
    title = fields.CharField(max_length=200, description="警报标题")
    message = fields.TextField(description="警报消息")
    alert_type = fields.CharField(
        max_length=20,
        description="警报类型: location-位置, sensor-传感器, security-安全, system-系统, maintenance-维护"
    )
    
    # 严重程度
    severity = fields.CharField(
        max_length=20,
        default="medium",
        description="严重程度: low-低, medium-中, high-高, critical-紧急"
    )
    
    # 关联对象
    cargo = fields.ForeignKeyField("models.Cargo", related_name="alerts", null=True, description="关联货物")
    equipment = fields.ForeignKeyField("models.Equipment", related_name="alerts", null=True, description="关联装备")
    device = fields.ForeignKeyField("models.TrackingDevice", related_name="alerts", null=True, description="关联设备")
    warehouse = fields.ForeignKeyField("models.Warehouse", related_name="alerts", null=True, description="关联仓库")
    
    # 状态信息
    status = fields.CharField(
        max_length=20,
        default="open",
        description="状态: open-开放, acknowledged-已确认, in_progress-处理中, resolved-已解决, closed-已关闭"
    )
    
    # 处理信息
    assigned_to = fields.ForeignKeyField("models.User", related_name="assigned_alerts", null=True, description="分配给")
    acknowledged_by = fields.ForeignKeyField("models.User", related_name="acknowledged_alerts", null=True, description="确认人")
    acknowledged_at = fields.DatetimeField(null=True, description="确认时间")
    resolved_by = fields.ForeignKeyField("models.User", related_name="resolved_alerts", null=True, description="解决人")
    resolved_at = fields.DatetimeField(null=True, description="解决时间")
    resolution_notes = fields.TextField(null=True, description="解决说明")
    
    # 时间信息
    occurred_at = fields.DatetimeField(description="发生时间")
    
    class Meta:
        table = "alerts"
        table_description = "警报表"


class AlertRule(BaseModel):
    """警报规则模型"""
    
    name = fields.CharField(max_length=200, description="规则名称")
    description = fields.TextField(null=True, description="规则描述")
    
    # 规则类型
    rule_type = fields.CharField(
        max_length=20,
        description="规则类型: threshold-阈值, geofence-地理围栏, pattern-模式, anomaly-异常"
    )
    
    # 规则条件
    conditions = fields.JSONField(description="规则条件(JSON)")
    
    # 警报配置
    alert_type = fields.CharField(max_length=20, description="警报类型")
    severity = fields.CharField(max_length=20, description="严重程度")
    message_template = fields.TextField(description="消息模板")
    
    # 通知配置
    notification_channels = fields.JSONField(null=True, description="通知渠道(JSON)")
    
    # 状态信息
    is_enabled = fields.BooleanField(default=True, description="是否启用")
    
    class Meta:
        table = "alert_rules"
        table_description = "警报规则表"


class RiskAssessment(BaseModel):
    """风险评估模型"""
    
    # 评估对象
    cargo = fields.ForeignKeyField("models.Cargo", related_name="risk_assessments", null=True, description="关联货物")
    equipment = fields.ForeignKeyField("models.Equipment", related_name="risk_assessments", null=True, description="关联装备")
    warehouse = fields.ForeignKeyField("models.Warehouse", related_name="risk_assessments", null=True, description="关联仓库")
    
    # 风险类型
    risk_type = fields.CharField(
        max_length=20,
        description="风险类型: theft-盗窃, damage-损坏, delay-延误, loss-丢失, environmental-环境"
    )
    
    # 风险等级
    risk_level = fields.CharField(
        max_length=20,
        description="风险等级: very_low-极低, low-低, medium-中, high-高, very_high-极高"
    )
    
    # 风险分数
    risk_score = fields.DecimalField(max_digits=5, decimal_places=2, description="风险分数(0-100)")
    
    # 评估详情
    risk_factors = fields.JSONField(description="风险因素(JSON)")
    mitigation_measures = fields.JSONField(null=True, description="缓解措施(JSON)")
    
    # 评估信息
    assessed_by = fields.ForeignKeyField("models.User", related_name="risk_assessments", description="评估人")
    assessment_method = fields.CharField(
        max_length=20,
        default="manual",
        description="评估方法: manual-人工, automatic-自动, hybrid-混合"
    )
    
    # 有效期
    valid_from = fields.DatetimeField(description="有效开始时间")
    valid_until = fields.DatetimeField(null=True, description="有效结束时间")
    
    class Meta:
        table = "risk_assessments"
        table_description = "风险评估表"


class AnomalyDetection(BaseModel):
    """异常检测模型"""
    
    # 检测对象
    cargo = fields.ForeignKeyField("models.Cargo", related_name="anomaly_detections", null=True, description="关联货物")
    equipment = fields.ForeignKeyField("models.Equipment", related_name="anomaly_detections", null=True, description="关联装备")
    device = fields.ForeignKeyField("models.TrackingDevice", related_name="anomaly_detections", null=True, description="关联设备")
    
    # 异常类型
    anomaly_type = fields.CharField(
        max_length=20,
        description="异常类型: location-位置异常, sensor-传感器异常, behavior-行为异常, pattern-模式异常"
    )
    
    # 异常详情
    anomaly_score = fields.DecimalField(max_digits=5, decimal_places=2, description="异常分数(0-100)")
    confidence = fields.DecimalField(max_digits=5, decimal_places=2, description="置信度(0-100)")
    description = fields.TextField(description="异常描述")
    
    # 检测信息
    detection_method = fields.CharField(max_length=50, description="检测方法")
    model_version = fields.CharField(max_length=20, null=True, description="模型版本")
    
    # 处理状态
    status = fields.CharField(
        max_length=20,
        default="detected",
        description="状态: detected-已检测, investigating-调查中, confirmed-已确认, false_positive-误报"
    )
    
    # 时间信息
    detected_at = fields.DatetimeField(description="检测时间")
    
    class Meta:
        table = "anomaly_detections"
        table_description = "异常检测表"
